package edu.cicese.alz.reports;

import edu.cicese.alz.DataUtil;
import edu.cicese.alz.FrameReport;
import edu.cicese.alz.TimeUtil;
import edu.cicese.alz.swing.ActivityThresholdRenderer;
import edu.cicese.alz.swing.DynamicCardLayout;
import edu.cicese.alz.swing.IntegerDocumentFilter;
import edu.cicese.alz.swing.IntensityChangeListener;
import edu.cicese.alz.swing.JColorButton;
import edu.cicese.alz.swing.JNonEmptyTextField;
import edu.cicese.alz.swing.SwingUtil;
import edu.cicese.alz.swing.calendar.DateChooser;
import edu.cicese.alz.swing.calendar.TextFieldDateEditor;
import edu.cicese.alz.util.PropertyUtil;

import javax.swing.Box;
import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.text.AbstractDocument;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.TreeSet;

/**
 * Created by: Eduardo Quintana Contreras
 * Date: 3/07/12
 * Time: 02:52 PM
 */
public class AccelerometerPane extends ReportPane {

	private JToggleButton btnTypeIntensity, btnTypeMagnitude;
	private Box boxAccelerometer;

	private TextFieldDateEditor txtMagnitudeDay;
	private DateChooser dMagnitudeDay;
	protected JSpinner sIntervalFrom;
	protected JSpinner sIntervalTo;

	private JRadioButton rbtIntensityAll, rbtIntensityFrom;
	protected DateChooser dIntensityFrom, dIntensityTo;
	private TextFieldDateEditor txtIntensityFrom, txtIntensityTo;

	protected JColorButton btnMagnitudeColor, btnColorNoData, btnColorNoMovement, btnColorSedentary,
			btnColorLight, btnColorModerate, btnColorHard;

	protected JNonEmptyTextField txtAdvancedEpoch, txtAdvancedMinimum;
	protected JComboBox cmbAdvancedAlpha;

	protected JNonEmptyTextField txtSedentaryFrom;
	protected JNonEmptyTextField txtLightFrom;
	protected JNonEmptyTextField txtModerateFrom;
	protected JNonEmptyTextField txtHardFrom;

	private JComboBox cmbThresholds;

	private BlockAccelerometerPreview pIntensityPreview;

	public AccelerometerPane() {
		initComponents();
		initOptionScrollPane(boxAccelerometer);
		loadOptions();
	}


	private void initComponents() {
		// Type
		btnTypeIntensity = SwingUtil.createToggleButton("", "Intensity", getIcon("acc_block"));
		btnTypeMagnitude = SwingUtil.createToggleButton("", "Magnitude", getIcon("acc_magnitude"));

		Box boxTypes = createHorizontalBox(new Component[]{
				Box.createHorizontalGlue(),
				btnTypeIntensity,
				Box.createHorizontalStrut(5),
				btnTypeMagnitude,
				Box.createHorizontalGlue()
		});

		Box boxTypeContent = createVerticalBox(new Component[]{
				boxTypes
		});

		// Users
		Box boxUsersContent = createUsersBox();

		// Period
		txtMagnitudeDay = new TextFieldDateEditor();
		txtMagnitudeDay.setDocument(FrameReport.txtDayFromModel);
		dMagnitudeDay = new DateChooser(new Date(), "dd-MM-yyyy", txtMagnitudeDay);

		Box boxMagnitudePeriod = createHorizontalBox(new Component[]{
				new JLabel("Day:"),
				Box.createHorizontalStrut(5),
				dMagnitudeDay
		});

		rbtIntensityAll = SwingUtil.createRadioButton("All");
		rbtIntensityAll.setModel(FrameReport.rbtPeriodAllModel);
		rbtIntensityFrom = SwingUtil.createRadioButton("From:");
		rbtIntensityFrom.setModel(FrameReport.rbtPeriodFromModel);
		ButtonGroup rgBlock = new ButtonGroup();
		rgBlock.add(rbtIntensityAll);
		rgBlock.add(rbtIntensityFrom);

		txtIntensityFrom = new TextFieldDateEditor();
		txtIntensityFrom.setDocument(FrameReport.txtDayFromModel);

		txtIntensityTo = new TextFieldDateEditor();
		txtIntensityTo.setDocument(FrameReport.txtDayToModel);

		txtIntensityFrom.getDocument().addDocumentListener(new DateDocumentListener(txtIntensityFrom, txtIntensityTo));
		dIntensityFrom = new DateChooser(new Date(), "dd-MM-yyyy", txtIntensityFrom);

		txtIntensityTo.getDocument().addDocumentListener(new DateDocumentListener(txtIntensityFrom, txtIntensityTo));
		dIntensityTo = new DateChooser(new Date(), "dd-MM-yyyy", txtIntensityTo);

		Box boxBlockDays = createHorizontalBox(new Component[]{
				rbtIntensityFrom,
				Box.createHorizontalStrut(5),
				dIntensityFrom,
				Box.createHorizontalStrut(3),
				new JLabel("to:"),
				Box.createHorizontalStrut(5),
				dIntensityTo
		});

		Box boxBlockPeriod = createVerticalBox(new Component[]{
				rbtIntensityAll,
				boxBlockDays
		}, 0);

		final JPanel pPeriodContent = createCardPane(new DynamicCardLayout());
		pPeriodContent.add("intensity", boxBlockPeriod);
		pPeriodContent.add("magnitude", boxMagnitudePeriod);

		sIntervalFrom = SwingUtil.createSpinner(new Date(), FrameReport.sHourFromModel);
		sIntervalTo = SwingUtil.createSpinner(new Date(), FrameReport.sHourToModel);

		Box boxInterval = createHorizontalBox(new Component[]{
				new JLabel("From:"),
				Box.createHorizontalStrut(5),
				sIntervalFrom,
				Box.createHorizontalStrut(5),
				new JLabel("to:"),
				Box.createHorizontalStrut(5),
				sIntervalTo
		});

		Box boxPeriod1 = createVerticalBox(new Component[]{
				pPeriodContent
		});

		Box boxPeriod2 = createVerticalBox(new Component[]{
				boxInterval
		});

		JPanel pPeriod = createContentPane(new Box[]{
				boxPeriod1,
				boxPeriod2
		});


		// Saving options
		Box boxSavingContent = createSavingBox();


		// Visualization
		btnMagnitudeColor = SwingUtil.createColorButton(20, 20);

		Box boxMagnitudeColors = createVerticalBox(new Component[]{
				createHorizontalColorBox(btnMagnitudeColor, "Magnitude Line")
		});

		btnColorNoData = SwingUtil.createColorButton(20, 20);
		btnColorNoData.addPropertyChangeListener(new BlockColorChangeListener());
		btnColorNoMovement = SwingUtil.createColorButton(20, 20);
		btnColorNoMovement.addPropertyChangeListener(new BlockColorChangeListener());
		btnColorSedentary = SwingUtil.createColorButton(20, 20);
		btnColorSedentary.addPropertyChangeListener(new BlockColorChangeListener());
		btnColorLight = SwingUtil.createColorButton(20, 20);
		btnColorLight.addPropertyChangeListener(new BlockColorChangeListener());
		btnColorModerate = SwingUtil.createColorButton(20, 20);
		btnColorModerate.addPropertyChangeListener(new BlockColorChangeListener());
		btnColorHard = SwingUtil.createColorButton(20, 20);
		btnColorHard.addPropertyChangeListener(new BlockColorChangeListener());

		Box boxIntensityColors1 = createVerticalBox(new Component[]{
				createHorizontalColorBox(btnColorNoData, "No Data"),
				Box.createVerticalStrut(2),
				createHorizontalColorBox(btnColorNoMovement, "No Movement"),
				Box.createVerticalStrut(2),
				createHorizontalColorBox(btnColorSedentary, "Sedentary")
		});
		Box boxIntensityColors2 = createVerticalBox(new Component[]{
				createHorizontalColorBox(btnColorLight, "Light"),
				Box.createVerticalStrut(2),
				createHorizontalColorBox(btnColorModerate, "Moderate"),
				Box.createVerticalStrut(2),
				createHorizontalColorBox(btnColorHard, "Hard")

		}, 30);

		JPanel pIntensityColors = createContentPane(new Box[]{
				boxIntensityColors1,
				boxIntensityColors2
		});

//		Box boxIntensityColors = createHorizontalBox(new Component[]{
//				pIntensityColors
//		});


		// Advanced options
		txtAdvancedEpoch = SwingUtil.createNonEmptyTextField(30, 20);
		txtAdvancedEpoch.getDocument().addDocumentListener(new EmptyTextListener(txtAdvancedEpoch));
		((AbstractDocument) txtAdvancedEpoch.getDocument()).setDocumentFilter(new IntegerDocumentFilter(txtAdvancedEpoch));

		txtAdvancedMinimum = SwingUtil.createNonEmptyTextField(30, 20);
		txtAdvancedMinimum.getDocument().addDocumentListener(new EmptyTextListener(txtAdvancedMinimum));
		((AbstractDocument) txtAdvancedMinimum.getDocument()).setDocumentFilter(new IntegerDocumentFilter(txtAdvancedMinimum));
		cmbAdvancedAlpha = SwingUtil.createComboBox(
				new Float[]{0.1f, 0.2f, 0.3f, 0.4f, 0.5f, 0.6f, 0.7f, 0.8f, 0.9f, 1.0f}, 47, 20);


		Box boxAdvancedAlpha = createHorizontalBox(new Component[]{
				SwingUtil.createLabel("Alpha:", 90, 20),
				cmbAdvancedAlpha
		});

		Box boxAdvancedEpoch = createHorizontalBox(new Component[]{
				SwingUtil.createLabel("Epoch duration:", 90, 20),
				txtAdvancedEpoch,
				Box.createHorizontalStrut(2),
				new JLabel("min.")
		});

		Box boxAdvancedMinimum = createHorizontalBox(new Component[]{
				SwingUtil.createLabel("Minimum:", 90, 20),
				txtAdvancedMinimum,
				Box.createHorizontalStrut(2),
				SwingUtil.createLabel("min.", 200, 20),
		});

		Box boxIntensityGeneral = createVerticalBox(new Component[]{
				boxAdvancedAlpha,
				Box.createVerticalStrut(2),
				boxAdvancedEpoch,
				Box.createVerticalStrut(2),
				boxAdvancedMinimum
		});

		txtSedentaryFrom = SwingUtil.createNonEmptyTextField(40, 20, JTextField.CENTER);
		JNonEmptyTextField txtSedentaryTo = SwingUtil.createNonEmptyTextField(40, 20, JTextField.CENTER, false);
		txtLightFrom = SwingUtil.createNonEmptyTextField(40, 20, JTextField.CENTER);
		JNonEmptyTextField txtLightTo = SwingUtil.createNonEmptyTextField(40, 20, JTextField.CENTER, false);
		txtModerateFrom = SwingUtil.createNonEmptyTextField(40, 20, JTextField.CENTER);
		JNonEmptyTextField txtModerateTo = SwingUtil.createNonEmptyTextField(40, 20, JTextField.CENTER, false);
		txtHardFrom = SwingUtil.createNonEmptyTextField(40, 20, JTextField.CENTER);
		JNonEmptyTextField txtHardTo = SwingUtil.createNonEmptyTextField(40, 20, JTextField.CENTER, false);
		txtHardTo.setText("\u221e");

		JNonEmptyTextField[] txtIntensities = new JNonEmptyTextField[]{txtSedentaryFrom, txtLightFrom, txtModerateFrom, txtHardFrom};

		txtSedentaryFrom.getDocument().addDocumentListener(new EmptyTextListener(txtSedentaryFrom));
		txtLightFrom.getDocument().addDocumentListener(new IntensityChangeListener(txtLightFrom, txtSedentaryTo, txtIntensities));
		txtModerateFrom.getDocument().addDocumentListener(new IntensityChangeListener(txtModerateFrom, txtLightTo, txtIntensities));
		txtHardFrom.getDocument().addDocumentListener(new IntensityChangeListener(txtHardFrom, txtModerateTo, txtIntensities));

		((AbstractDocument) txtSedentaryFrom.getDocument()).setDocumentFilter(new IntegerDocumentFilter(txtSedentaryFrom));
		((AbstractDocument) txtLightFrom.getDocument()).setDocumentFilter(new IntegerDocumentFilter(txtLightFrom));
		((AbstractDocument) txtModerateFrom.getDocument()).setDocumentFilter(new IntegerDocumentFilter(txtModerateFrom));
		((AbstractDocument) txtHardFrom.getDocument()).setDocumentFilter(new IntegerDocumentFilter(txtHardFrom));

		JLabel[] lblIntensities = new JLabel[4];
		for (int i = 0; i < lblIntensities.length; i++) {
			lblIntensities[i] = SwingUtil.createLabel("-", 10, 20);
			lblIntensities[i].setHorizontalAlignment(JLabel.CENTER);
		}

		Box boxAdvancedSedentary = createHorizontalBox(new Component[]{
				SwingUtil.createLabel("Sedentary:", 60, 20),
				txtSedentaryFrom,
				Box.createHorizontalStrut(2),
				lblIntensities[0],
				Box.createHorizontalStrut(2),
				txtSedentaryTo
		});

		Box boxAdvancedLight = createHorizontalBox(new Component[]{
				SwingUtil.createLabel("Light:", 60, 20),
				txtLightFrom,
				Box.createHorizontalStrut(2),
				lblIntensities[1],
				Box.createHorizontalStrut(2),
				txtLightTo
		});

		Box boxAdvancedModerate = createHorizontalBox(new Component[]{
				SwingUtil.createLabel("Moderate:", 60, 20),
				txtModerateFrom,
				Box.createHorizontalStrut(2),
				lblIntensities[2],
				Box.createHorizontalStrut(2),
				txtModerateTo
		});

		Box boxAdvancedHard = createHorizontalBox(new Component[]{
				SwingUtil.createLabel("Hard:", 60, 20),
				txtHardFrom,
				Box.createHorizontalStrut(2),
				lblIntensities[3],
				Box.createHorizontalStrut(2),
				txtHardTo
		});

		cmbThresholds = SwingUtil.createComboBox(new String[]{}, 125, 20);
		cmbThresholds.setRenderer(new ActivityThresholdRenderer());
		cmbThresholds.addActionListener(new ThresholdActionListener());

		populateThresholds();

		Box boxActivity1 = createVerticalBox(new Component[]{
				boxAdvancedSedentary,
				Box.createVerticalStrut(2),
				boxAdvancedLight,
				Box.createVerticalStrut(2),
				boxAdvancedModerate,
				Box.createVerticalStrut(2),
				boxAdvancedHard
		});

		Box boxActivity2 = createVerticalBox(new Component[] {
				cmbThresholds
		}, 10);

		JPanel pActivity = createContentPane(new Box[] {
				boxActivity1, boxActivity2
		});
		
		Box boxIntensity1 = createVerticalBox(new Component[]{
				boxIntensityGeneral,
				Box.createVerticalStrut(4),
				createTitlePane("Colors", SwingUtil.cBackground),
				Box.createVerticalStrut(7),
				pIntensityColors,
				Box.createVerticalStrut(4),
				createTitlePane("Activity count thresholds", SwingUtil.cBackground),
				Box.createVerticalStrut(7),
				pActivity
		}, 0);

		pIntensityPreview = new BlockAccelerometerPreview();
		Box boxIntensity2 = createVerticalBox(new Component[]{
				createTitlePane("Preview", SwingUtil.cBackground),
				Box.createVerticalStrut(4),
				pIntensityPreview
		});

		JPanel pIntensity = createContentPane(new Box[]{
				boxIntensity1,
				boxIntensity2
		});

		final JPanel pAdvanced = createCardPane(new DynamicCardLayout());
		pAdvanced.add("intensity", pIntensity);
		pAdvanced.add("magnitude", boxMagnitudeColors);

		boxAccelerometer = Box.createVerticalBox();

		boxAccelerometer.add(createTitlePane("Chart type"));
		boxAccelerometer.add(Box.createVerticalStrut(7));
		boxAccelerometer.add(boxTypeContent);
		boxAccelerometer.add(Box.createVerticalStrut(7));

		boxAccelerometer.add(createTitlePane("User(s)"));
		boxAccelerometer.add(Box.createVerticalStrut(4));
		boxAccelerometer.add(boxUsersContent);
		boxAccelerometer.add(Box.createVerticalStrut(4));

		boxAccelerometer.add(createTitlePane("Period"));
		boxAccelerometer.add(Box.createVerticalStrut(4));
		boxAccelerometer.add(pPeriod);
		boxAccelerometer.add(Box.createVerticalStrut(4));

		boxAccelerometer.add(createTitlePane("Saving options"));
		boxAccelerometer.add(Box.createVerticalStrut(4));
		boxAccelerometer.add(boxSavingContent);
		boxAccelerometer.add(Box.createVerticalStrut(4));

		boxAccelerometer.add(createTitlePane("Advanced options"));
		boxAccelerometer.add(Box.createVerticalStrut(7));
		boxAccelerometer.add(pAdvanced);
		boxAccelerometer.add(Box.createVerticalStrut(6));

		ButtonGroup btnGroup = new ButtonGroup();
		btnGroup.add(btnTypeIntensity);
		btnGroup.add(btnTypeMagnitude);

		btnTypeIntensity.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				CardLayout cardLayoutPeriod = (CardLayout) pPeriodContent.getLayout();
				CardLayout cardLayoutColor = (CardLayout) pAdvanced.getLayout();
				if (btnTypeIntensity.isSelected()) {
					cardLayoutPeriod.show(pPeriodContent, "intensity");
					cardLayoutColor.show(pAdvanced, "intensity");
					btnTypeMagnitude.setBorder(new EmptyBorder(3, 3, 3, 3));
				} else {
					cardLayoutPeriod.show(pPeriodContent, "magnitude");
					cardLayoutColor.show(pAdvanced, "magnitude");
					btnTypeMagnitude.setBorder(new LineBorder(SwingUtil.cRolloverBorder, 3));
				}
			}
		});

		btnTypeMagnitude.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				CardLayout cardLayoutPeriod = (CardLayout) pPeriodContent.getLayout();
				CardLayout cardLayoutColor = (CardLayout) pAdvanced.getLayout();
				if (btnTypeMagnitude.isSelected()) {
					cardLayoutPeriod.show(pPeriodContent, "magnitude");
					cardLayoutColor.show(pAdvanced, "magnitude");
					btnTypeIntensity.setBorder(new EmptyBorder(3, 3, 3, 3));
				} else {
					cardLayoutPeriod.show(pPeriodContent, "intensity");
					cardLayoutColor.show(pAdvanced, "intensity");
					btnTypeIntensity.setBorder(new LineBorder(SwingUtil.cRolloverBorder, 3));
				}
			}
		});
	}


	public void loadOptions() {
		boolean error = false;

		// Type
		if (PropertyUtil.getProperty(PropertyUtil.REP_ACC_TYPE).equals("block")) {
			btnTypeIntensity.setSelected(true);
		}
		btnTypeMagnitude.setSelected(!btnTypeIntensity.isSelected());

		// Users
		try {
			rbtUsersAll.setSelected(PropertyUtil.getBoolean(PropertyUtil.REP_USERS_ALL));
			txtUsers.setText(PropertyUtil.getProperty(PropertyUtil.REP_USERS));
		} catch (Exception e) {
			e.printStackTrace();
			error = true;
		}
		rbtUsers.setSelected(!rbtUsersAll.isSelected());

		// Period
		try {
			rbtIntensityAll.setSelected(PropertyUtil.getBoolean(PropertyUtil.REP_PERIOD_ALL));
		} catch (Exception e) {
			e.printStackTrace();
			error = true;
		}
		rbtIntensityFrom.setSelected(!rbtIntensityAll.isSelected());

		try {
			dIntensityFrom.setDate(PropertyUtil.getDate(PropertyUtil.REP_PERIOD_FROM));
			dIntensityTo.setDate(PropertyUtil.getDate(PropertyUtil.REP_PERIOD_TO));
		} catch (Exception e) {
			e.printStackTrace();
			error = true;
		}

		try {
			sIntervalFrom.setValue(TimeUtil.getDate(PropertyUtil.getProperty(PropertyUtil.REP_INTERVAL_FROM)));
			sIntervalTo.setValue(TimeUtil.getDate(PropertyUtil.getProperty(PropertyUtil.REP_INTERVAL_TO)));
		} catch (Exception e) {
			e.printStackTrace();
			error = true;
		}

		// Saving options
		try {
			chbSaveCharts.setSelected(PropertyUtil.getBoolean(PropertyUtil.REP_SAVE_CHARTS));
			chbShowCharts.setSelected(PropertyUtil.getBoolean(PropertyUtil.REP_SHOW_CHARTS));
		} catch (Exception e) {
			e.printStackTrace();
			error = true;
		}

		// Advanced options
		try {
			cmbAdvancedAlpha.setSelectedItem(Float.valueOf(PropertyUtil.getProperty(PropertyUtil.REP_ACC_ADVANCED_ALPHA)));
			txtAdvancedEpoch.setText(PropertyUtil.getProperty(PropertyUtil.REP_ACC_ADVANCED_EPOCH));
			txtAdvancedMinimum.setText(PropertyUtil.getProperty(PropertyUtil.REP_ACC_ADVANCED_MINIMUM));
		} catch (Exception e) {
			e.printStackTrace();
			error = true;
		}

		// colors
		try {
			btnColorNoData.setBackground(PropertyUtil.getColor(PropertyUtil.REP_ACC_INTENSITY_COLOR_NO_DATA));
			btnColorNoMovement.setBackground(PropertyUtil.getColor(PropertyUtil.REP_ACC_INTENSITY_COLOR_NO_MOVEMENT));
			btnColorSedentary.setBackground(PropertyUtil.getColor(PropertyUtil.REP_ACC_INTENSITY_COLOR_SEDENTARY));
			btnColorLight.setBackground(PropertyUtil.getColor(PropertyUtil.REP_ACC_INTENSITY_COLOR_LIGHT));
			btnColorModerate.setBackground(PropertyUtil.getColor(PropertyUtil.REP_ACC_INTENSITY_COLOR_MODERATE));
			btnColorHard.setBackground(PropertyUtil.getColor(PropertyUtil.REP_ACC_INTENSITY_COLOR_HARD));

			btnMagnitudeColor.setBackground(PropertyUtil.getColor(PropertyUtil.REP_ACC_MAGNITUDE_COLOR_MAGNITUDE));
		} catch (Exception e) {
			e.printStackTrace();
			error = true;
		}

		// activity count thresholds
		try {
			txtSedentaryFrom.setText(PropertyUtil.getProperty(PropertyUtil.REP_ACC_INTENSITY_THRESHOLD_SEDENTARY));
			txtLightFrom.setText(PropertyUtil.getProperty(PropertyUtil.REP_ACC_INTENSITY_THRESHOLD_LIGHT));
			txtModerateFrom.setText(PropertyUtil.getProperty(PropertyUtil.REP_ACC_INTENSITY_THRESHOLD_MODERATE));
			txtHardFrom.setText(PropertyUtil.getProperty(PropertyUtil.REP_ACC_INTENSITY_THRESHOLD_HARD));
		} catch (Exception e) {
			e.printStackTrace();
			error = true;
		}

		if (error) {
			System.out.println("An error occurred loading saved options.");
			loadDefaultOptions();
		}

		repaintBlockPreview();
	}

	public void saveOptions() {
		// Type
		PropertyUtil.setProperty(PropertyUtil.REP_GPS_TYPE, btnTypeIntensity.isSelected() ? "block" : "intensity");

		// Users
		PropertyUtil.setProperty(PropertyUtil.REP_USERS_ALL, String.valueOf(rbtUsersAll.isSelected()));
		PropertyUtil.setProperty(PropertyUtil.REP_USERS, txtUsers.getText());

		// Period
		PropertyUtil.setProperty(PropertyUtil.REP_PERIOD_ALL, String.valueOf(rbtIntensityAll.isSelected()));
		if (!txtIntensityFrom.hasDateError() || !txtIntensityFrom.hasFormatError()) {
			PropertyUtil.setProperty(PropertyUtil.REP_PERIOD_FROM, SwingUtil.calendarDateFormat.format(dIntensityFrom.getDate()));
		}
		if (!txtIntensityTo.hasDateError() || !txtIntensityTo.hasFormatError()) {
			PropertyUtil.setProperty(PropertyUtil.REP_PERIOD_TO, SwingUtil.calendarDateFormat.format(dIntensityTo.getDate()));
		}
		PropertyUtil.setProperty(PropertyUtil.REP_INTERVAL_FROM, SwingUtil.timeFormat.format(sIntervalFrom.getValue()));
		PropertyUtil.setProperty(PropertyUtil.REP_INTERVAL_TO, SwingUtil.timeFormat.format(sIntervalTo.getValue()));

		// Saving options
		PropertyUtil.setProperty(PropertyUtil.REP_SHOW_CHARTS, String.valueOf(chbShowCharts.isSelected()));
		PropertyUtil.setProperty(PropertyUtil.REP_SAVE_CHARTS, String.valueOf(chbSaveCharts.isSelected()));

		// Advanced options
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_ADVANCED_ALPHA, String.valueOf(cmbAdvancedAlpha.getSelectedItem()));

		// INTENSITY
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_ADVANCED_EPOCH, txtAdvancedEpoch.getText());
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_ADVANCED_MINIMUM, txtAdvancedMinimum.getText());

		// colors
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_INTENSITY_COLOR_NO_DATA, String.valueOf(btnColorNoData.getBackground().getRGB()));
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_INTENSITY_COLOR_NO_MOVEMENT, String.valueOf(btnColorNoMovement.getBackground().getRGB()));
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_INTENSITY_COLOR_SEDENTARY, String.valueOf(btnColorSedentary.getBackground().getRGB()));
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_INTENSITY_COLOR_LIGHT, String.valueOf(btnColorLight.getBackground().getRGB()));
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_INTENSITY_COLOR_MODERATE, String.valueOf(btnColorModerate.getBackground().getRGB()));
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_INTENSITY_COLOR_HARD, String.valueOf(btnColorHard.getBackground().getRGB()));

		// activity count thresholds
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_INTENSITY_THRESHOLD_SEDENTARY, txtSedentaryFrom.getText());
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_INTENSITY_THRESHOLD_LIGHT, txtLightFrom.getText());
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_INTENSITY_THRESHOLD_MODERATE, txtModerateFrom.getText());
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_INTENSITY_THRESHOLD_HARD, txtHardFrom.getText());

		// MAGNITUDE
		PropertyUtil.setProperty(PropertyUtil.REP_ACC_MAGNITUDE_COLOR_MAGNITUDE, String.valueOf(btnMagnitudeColor.getBackground().getRGB()));
	}

	public void loadDefaultOptions() {
		PropertyUtil.setDefaultAccelerometerProperties();
		loadOptions();
	}

	public void generate() {
		try {
			sIntervalFrom.commitEdit();
			sIntervalTo.commitEdit();
		} catch (ParseException e) { /*ignored*/ }
		
		//TODO Check errors

		TreeSet<Integer> userIDs = null;
		if (!rbtUsersAll.isSelected()) {
			if (!txtUsers.hasError()) {
				userIDs = getUsers(txtUsers);
			} else {
				//show dialog with error
			}
		} else {
			// get all the subjects in the DB
			userIDs = getUsers();
		}
		if (btnTypeIntensity.isSelected()) {

			for (int userID = 1; userID <= 15; userID++) {
				System.out.println("\nUser: " + userID + "\n");

				userIDs.clear();
				userIDs.add(userID);

				Date begin = TimeUtil.getDate(DataUtil.dates[userID - 1][0], TimeUtil.sdfDateOnly);
				Calendar cal = Calendar.getInstance();
				cal.setTime(begin);
				cal.add(Calendar.DAY_OF_YEAR, 1);
				begin = cal.getTime();

				Date end = TimeUtil.getDate(DataUtil.dates[userID - 1][1], TimeUtil.sdfDateOnly);
				cal.setTime(end);
				cal.add(Calendar.DAY_OF_YEAR, -1);
				end = cal.getTime();

				AccelerometerReport accelerometerReport = new AccelerometerReport(
						userIDs,
						begin,
						end,
						(Date) sIntervalFrom.getValue(),
						(Date) sIntervalTo.getValue(),
						chbShowCharts.isSelected(),
						chbSaveCharts.isSelected(),
						AccelerometerReport.TYPE_INTENSITY,
						(Float) cmbAdvancedAlpha.getSelectedItem());

				accelerometerReport.setIntensitySettings(
						Integer.valueOf(txtAdvancedEpoch.getText()),
						Integer.valueOf(txtAdvancedMinimum.getText()),
						btnColorNoData.getBackground(),
						btnColorNoMovement.getBackground(),
						btnColorSedentary.getBackground(),
						btnColorLight.getBackground(),
						btnColorModerate.getBackground(),
						btnColorHard.getBackground(),
						Integer.valueOf(txtSedentaryFrom.getText()),
						Integer.valueOf(txtLightFrom.getText()),
						Integer.valueOf(txtModerateFrom.getText()),
						Integer.valueOf(txtHardFrom.getText()));

				accelerometerReport.createCharts();
			}

			//TODO Uncomment
//			AccelerometerReport accelerometerReport = new AccelerometerReport(
//					userIDs,
//					dIntensityFrom.getDate(),
//					dIntensityTo.getDate(),
//					(Date) sIntervalFrom.getValue(),
//					(Date) sIntervalTo.getValue(),
//					chbShowCharts.isSelected(),
//					chbSaveCharts.isSelected(),
//					AccelerometerReport.TYPE_INTENSITY,
//					(Float) cmbAdvancedAlpha.getSelectedItem());
//
//			accelerometerReport.setIntensitySettings(
//					Integer.valueOf(txtAdvancedEpoch.getText()),
//					Integer.valueOf(txtAdvancedMinimum.getText()),
//					btnColorNoData.getBackground(),
//					btnColorNoMovement.getBackground(),
//					btnColorSedentary.getBackground(),
//					btnColorLight.getBackground(),
//					btnColorModerate.getBackground(),
//					btnColorHard.getBackground(),
//					Integer.valueOf(txtSedentaryFrom.getText()),
//					Integer.valueOf(txtLightFrom.getText()),
//					Integer.valueOf(txtModerateFrom.getText()),
//					Integer.valueOf(txtHardFrom.getText()));
//
//			accelerometerReport.createCharts();
		}
	}


	private void repaintBlockPreview() {
		Color[] colors = new Color[]{
				btnColorNoData.getBackground(), btnColorNoMovement.getBackground(),
				btnColorSedentary.getBackground(), btnColorLight.getBackground(),
				btnColorModerate.getBackground(), btnColorHard.getBackground()};

		pIntensityPreview.setAccelerometerColors(colors);
		pIntensityPreview.repaint();
	}

	private void populateThresholds() {
		//TODO add more values
		cmbThresholds.addItem(new ActivityThresholds("NQLS", "Adults: 18+ years", 1, 101, 1953, 5725));
		cmbThresholds.addItem(new ActivityThresholds("LIFE-P", "Seniors: 70->85 years", 1, 149, 1832, Short.MAX_VALUE));
		cmbThresholds.addItem(new ActivityThresholds("Troiano et al. 2007", "Adults: 18+ years (national sample)", 1, 101, 2020, 5999));
		cmbThresholds.addItem(new ActivityThresholds("Navarro R, 2013", "Adults: 65+ years (test)", 1, 21, 501, 1001));
	}

	private ActivityThresholds getSelectedThresholds() {
		return (ActivityThresholds) cmbThresholds.getSelectedItem();
	}

	private void loadThresholds() {
		ActivityThresholds values = getSelectedThresholds();
		txtSedentaryFrom.setText(values.getSedentary() + "");
		txtLightFrom.setText(values.getLight() + "");
		txtModerateFrom.setText(values.getModerate() + "");
		txtHardFrom.setText(values.getHard() + "");
	}


	class BlockColorChangeListener implements PropertyChangeListener {
		@Override
		public void propertyChange(PropertyChangeEvent evt) {
			if (evt.getPropertyName().equals("background")) {
				repaintBlockPreview();
			}
		}
	}

	class ThresholdActionListener implements ActionListener {
		@Override
		public void actionPerformed(ActionEvent e) {
			if (cmbThresholds.getSelectedIndex() != -1) {
				loadThresholds();
			}
		}
	}
}
